<template>
  <!-- 条件查询 -->
     <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="编号">
      <el-input v-model="formInline.Carrier_Number" placeholder="请输入编号" clearable />
    </el-form-item>
     <el-form-item label="单元名称">
      <el-input v-model="formInline.Carrier_Name" placeholder="请输入名称" clearable />
    </el-form-item>

    
    <el-form-item>
      <el-button type="primary" @click="getdata()">查询</el-button>
    </el-form-item>
  </el-form>


   <!-- 页面数据 -->
  <el-button plain @click="AddWarehouse()">
新增
  </el-button>
     <el-button plain @click="handleExport()">
导出
  </el-button>

  
 <el-table :data="tableData" style="width: 100%">
  <el-table-column prop="carrier_Number" label="承运商编号" width="100" />
    <el-table-column prop="carrier_Name" label="承运商名称" width="100"  />
    <el-table-column prop="notes" label="备注" width="100" />
     <el-table-column fixed="right" label="操作" width="250">
      <template #default="scoped">
        <el-button type="primary" @click="UpdateWarehouse(scoped.row)">编辑</el-button>
      <el-button type="danger" @click="del(scoped.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[15, 20, 25, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      prev-text="上一页"
      next-text="下一页"
      :total="page.totalCount"
    />

    <!-- 新增弹窗 -->
<el-dialog
    v-model="dialogVisible"
    title="新增"
    width="500"
  >
 <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="承运商编号" prop="">
      <el-input v-model="ruleForm.carrier_Number" disabled/>
    </el-form-item>
    
    <el-form-item label="承运商名称" prop="">
      <el-input v-model="ruleForm.carrier_Name" />
    </el-form-item>
 

         <el-form-item label="描述" prop="">
      <el-input v-model="ruleForm.notes" type="textarea" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
    </el-form-item>
  </el-form>

  </el-dialog>

  <!-- 编辑弹窗 -->
<el-dialog
    v-model="updialogVisible"
    title="编辑"
    width="500"
  >
 <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
     <el-form-item label="承运商编号" prop="">
      <el-input v-model="ruleForm.carrier_Number" disabled/>
    </el-form-item>
    
    <el-form-item label="承运商名称" prop="">
      <el-input v-model="ruleForm.carrier_Name" />
    </el-form-item>
 

         <el-form-item label="描述" prop="">
      <el-input v-model="ruleForm.notes" type="textarea" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="updatesubmitForm(ruleFormRef)">
        提交
      </el-button>
    </el-form-item>
  </el-form>

  </el-dialog>
</template>

<script setup lang="ts">
import axios from 'axios'
import { reactive,onMounted, ref, watch } from 'vue'
import { BasicsRed } from '@/http/axiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { BasicsWrite } from '@/http/axiosHelper'
import { statementRed } from '@/http/axiosHelper'
const router=useRouter();
const dialogVisible = ref(false)
const updialogVisible = ref(false)
function formatDate(dateStr: string) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}

const AddWarehouse=()=>
{
   dialogVisible.value=true;
   ruleForm.carrier_Number= generateDateBasedNumber(),
  ruleForm.carrier_Name= "",
  ruleForm.notes= ""
}

const UpdateWarehouse=(row:any)=>
{
   Object.assign(ruleForm,row);
updialogVisible.value=true
}
const updatesubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
   BasicsWrite.post("/api/Carrier/UpdateCarrierHandle",ruleForm).then(res=>
    {
        if(res.data.code==200)
    {
        ElMessage.success(res.data.msg);

       
     

  updialogVisible.value=false;
     getdata()
    }
    else
    {
            ElMessage.success(res.data.msg);
    }
    }
   )
    }
  })
}


// 改进版 - 添加持久化支持
const generateDateBasedNumber = (incrementLength: number = 4) => {
  const now = new Date();
  const datePart = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
  
  // 从localStorage读取或初始化计数器
  const storageKey = `dateNumCounter_${datePart}`;
  let currentCount = localStorage.getItem(storageKey);
  
  // 如果localStorage中没有值，则初始化为0
  if (currentCount === null) {
    currentCount = '0';
  }
  
  // 转换为数字，递增，然后转回字符串
  const numericCount = parseInt(currentCount, 10) + 1;
  currentCount = numericCount.toString();
  
  // 保存新的计数器值
  localStorage.setItem(storageKey, currentCount);

  // 确保incrementLength是数字，然后生成递增部分
  const incrementPart = currentCount.padStart(incrementLength, '0');
  
  return datePart + incrementPart;
};

import {  type FormInstance, type FormRules } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id:0,
 "carrier_Number": generateDateBasedNumber(),
  "carrier_Name": "",
  "notes": ""
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  region: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'change',
    },
  ],
  count: [
    {
      required: true,
      message: 'Please select Activity count',
      trigger: 'change',
    },
  ],
  date1: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a date',
      trigger: 'change',
    },
  ],
  date2: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],
  location: [
    {
      required: true,
      message: 'Please select a location',
      trigger: 'change',
    },
  ],
  type: [
    {
      type: 'array',
      required: true,
      message: 'Please select at least one activity type',
      trigger: 'change',
    },
  ],
  resource: [
    {
      required: true,
      message: 'Please select activity resource',
      trigger: 'change',
    },
  ],
  desc: [
    { required: true, message: 'Please input activity form', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
   BasicsWrite.post("/api/Carrier/CreateCarrierHandle",ruleForm).then(res=>
    {
        if(res.data.code==200)
    {
        ElMessage.success(res.data.msg);

       
     ruleForm.carrier_Number= generateDateBasedNumber(),
  ruleForm.carrier_Name= "",
  ruleForm.notes= ""
 

  dialogVisible.value=false;
getdata()
    }
    else
    {
            ElMessage.success(res.data.msg);
    }
    }
   )
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}



const formInline = reactive({

  Carrier_Number: '',
  Carrier_Name: '',
  
})
const page=reactive({
    PageIndex:1,
    PageSize:15,
    totalCount:0

})
watch(page,()=>
{
  getdata();
})
onMounted(()=>
{
    delparmentdata();
    getdata();
})


const del=(id:any)=>
{

ElMessageBox.confirm(
    '确认删除吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
     BasicsWrite.put("/api/Carrier/DelCarrierHandle",{id:id}).then(res=>
{
   if(res.data.code==200)
   {
    ElMessage.success("删除成功");
    getdata();
   }
   else
   {
    ElMessage.success("删除失败");
   }
}
)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })




}

const deplarment=ref()
const delparmentdata=()=>
{
    BasicsRed.get("/api/Deparment/GetDepartmentHandle",{params:{PageIndex:page.PageIndex,PageSize:page.PageSize}}).then(res=>
        {
            deplarment.value=res.data.data
        }
    )
}

const tableData=ref([]);

const getdata=()=>
{
    BasicsRed.get("/api/Carriers/GetCarrierHandle",{params:{
      PageIndex:page.PageIndex,
      PageSize:page.PageSize,
      Carrier_Number:formInline.Carrier_Number,
      Carrier_Name:formInline.Carrier_Name
    
    
    
    }}).then(res=>
        {
tableData.value=res.data.data
page.totalCount=res.data.totalCount
        }
    )
}
// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
    try {
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await BasicsRed({
            url: '/api/Carriers/GetCarrierExport', // 后端接口地址
            method: 'GET',
            params: {
                  PageIndex:page.PageIndex,
                  PageSize:page.PageSize,
                  Carrier_Number:formInline.Carrier_Number,
                  Carrier_Name:formInline.Carrier_Name
            }, // 对应后端 [FromQuery] 的 command 参数
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

    } catch (error: any) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        alert('导出失败，请检查参数或重新登录');
    }
}


// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '承运商管理.xlsx'; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '承运商管理.xlsx';
}



const onSubmit = () => {
  console.log('submit!')
}
</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 120px;
}

.demo-form-inline .el-select {
  --el-select-width: 120px;
}
</style>